package com.tcoiss.message.service.impl;


import com.tcoiss.message.domain.MqBiz;
import com.tcoiss.message.domain.ReturnT;
import com.tcoiss.message.mapper.MqBizMapper;
import com.tcoiss.message.mapper.MqTopicMapper;
import com.tcoiss.message.service.IMqBizService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author xuxueli 2018-11-20
 */
@Service
public class MqBizServiceImpl implements IMqBizService {

    @Resource
    private MqBizMapper mqBizDao;
    @Resource
    private MqTopicMapper mqTopicDao;


    @Override
    public List<MqBiz> findAll() {
        return mqBizDao.findAll();
    }

    @Override
    public MqBiz load(int id) {
        return mqBizDao.load(id);
    }

    @Override
    public ReturnT<String> add(MqBiz mqBiz) {

        // valid
        if (mqBiz.getBizName()==null || mqBiz.getBizName().trim().length()==0) {
            return new ReturnT<>(ReturnT.FAIL_CODE, "业务线名称不可为空");
        }
        if (!(mqBiz.getBizName().trim().length()>=4 && mqBiz.getBizName().trim().length()<=64)) {
            return new ReturnT<>(ReturnT.FAIL_CODE, "业务线名称长度非法[2-64]");
        }

        // exist
        List<MqBiz> list = findAll();
        if (list != null) {
            for (MqBiz item: list) {
                if (item.getBizName().equals(mqBiz.getBizName())) {
                    return new ReturnT<>(ReturnT.FAIL_CODE, "业务线名称不可重复");
                }
            }
        }

        int ret = mqBizDao.add(mqBiz);
        return ret>0?ReturnT.SUCCESS:ReturnT.FAIL;
    }

    @Override
    public ReturnT<String> update(MqBiz mqBiz) {

        // valid
        if (mqBiz.getBizName()==null || mqBiz.getBizName().trim().length()==0) {
            return new ReturnT<>(ReturnT.FAIL_CODE, "业务线名称不可为空");
        }
        if (!(mqBiz.getBizName().trim().length()>=4 && mqBiz.getBizName().trim().length()<=64)) {
            return new ReturnT<>(ReturnT.FAIL_CODE, "业务线名称长度非法[2-64]");
        }

        // exist
        List<MqBiz> list = findAll();
        if (list != null) {
            for (MqBiz item: list) {
                if (item.getId()!=mqBiz.getId() && item.getBizName().equals(mqBiz.getBizName())) {
                    return new ReturnT<>(ReturnT.FAIL_CODE, "业务线名称不可重复");
                }
            }
        }

        int ret = mqBizDao.update(mqBiz);
        return ret>0?ReturnT.SUCCESS:ReturnT.FAIL;
    }

    @Override
    public ReturnT<String> delete(int id) {

        // valid limit not use
        int count = mqTopicDao.pageListCount(0, 1, id, null);
        if (count > 0) {
            return new ReturnT<>(ReturnT.FAIL_CODE, "禁止删除，该业务线下存在Topic");
        }

        int ret = mqBizDao.delete(id);
        return ret>0?ReturnT.SUCCESS:ReturnT.FAIL;
    }

}
